<template>
  <lan-dialog
    :config="editConfig"
    :formData="dataForm"
  >
    <template #slot="scope">
      <el-input
        :style="{ width: 300 + 'px' }"
        v-model="scope.data.slot"
        class="form-input"
      ></el-input>
    </template>
    <template #alarmMethod="scope">
      <el-select
        v-model="scope.data.alarmMethod"
        :style="{ width: 300 + 'px' }"
      >
        <el-option
          v-for="method in alarmMethodList"
          :key="method.value"
          :label="method.label"
          :value="method.value"
        ></el-option>
      </el-select>
    </template>
    <template #parameterId="scope">
      <el-select
        :style="{ width: 300 + 'px' }"
        class="input"
        v-model="scope.data.parameterId"
        placeholder="请选择"
        filterable
        remote
        reserve-keyword
        :remote-method="remoteParameterSearch"
        :loading="remoteLoading"
        clearable
        @focus="remoteParameterSearch()"
      >
        <el-option
          class="input"
          v-for="parameter in parameterList"
          :key="parameter.id"
          :label="parameter.label"
          :value="parameter.id"
        >
        </el-option>
      </el-select>
    </template>
    <template #active="scope">
      <el-switch v-model="scope.data.active"></el-switch>
    </template>
  </lan-dialog>
</template>

<script>
import { validateForm } from './servers';
import { generateAlarmTypeSelectorData } from './servers';
import { updateAlarmRuleApi, getAlarmRuleDetailApi } from '../../../api/alarmRule';
import { Message } from 'element-ui';
import { parseError } from '../../../utils';
import { queryDeviceTypeListApi } from '../../../api/deviceType';
import { AlarmMethod } from '../../../constants/alarm';
import { queryDeviceParameterListApi } from '../../../api/deviceParameter';
import lanDialog from '../../../components/lanDialog';

export default {
  name: 'EditAlarmRule',
  components: { lanDialog },
  data() {
    this.uuid = '';
    this.formLabelWidth = '120px';
    return {
      editConfig: {
        dialogVisible: false,
        title: '添加报警规则',
        type: 'add',
        inline: false,
        labelWidth: 200,
        formList: [
          {
            name: 'name',
            label: '报警规则名称',
            type: 'input',
            placeholder: '请输报警规则名称',
            required: true,
            tooltip: '报警规则的名称',
            width: 300
          },
          {
            name: 'alarmMethod',
            label: '报警比较方法',
            type: 'slot',
            required: true,
            tooltip: '设备参数值同预警阈值和报警阈值比较的方法（小于、小于等于、大于、大于等于）',
            width: 300
          },
          {
            name: 'parameterId',
            label: '设备参数',
            type: 'slot',
            required: true,
            tooltip: '设备的参数名称',
            width: 300
          },
          {
            name: 'alertThreshold',
            label: '预警阈值',
            type: 'input',
            required: true,
            tooltip: '设定的设备参数所对应的数值如果满足预警阈值，则会产生一次预警',
            placeholder: '请输入预警阈值',
            width: 300
          },
          {
            name: 'alarmThreshold',
            label: '报警阈值',
            type: 'input',
            required: true,
            tooltip: '设定的设备参数所对应的数值如果满足预警阈值，则会产生一次报警',
            placeholder: '请输入报警阈值',
            width: 300
          },
          {
            name: 'active',
            label: '开关状态',
            type: 'slot',
            required: true,
            tooltip: '是否启用该报警规则',
            width: 300
          }
        ],
        buttons: [
          {
            text: '取消',
            icon: '',
            type: '',
            method: () => {
              this.editConfig.dialogVisible = false;
            }
          },
          {
            text: '确认',
            icon: '',
            type: 'primary',
            method: () => {
              this.update();
              this.editConfig.dialogVisible = false;
            }
          }
        ]
      },
      dataForm: {
        name: '',
        alertThreshold: 0,
        alarmThreshold: 0,
        alarmMethod: '',
        active: true,
        alarmTypeList: [],
        deviceTypeUuidList: [],
        recipientUuidList: [],
        parameterId: ''
      },
      alarmTypeOptions: [],
      dialogVisible: false,
      btnLoading: false,
      remoteLoading: false,
      deviceTypeList: [],
      recipientList: [],
      parameterList: [],
      alarmMethodList: [
        {
          label: '小于',
          value: AlarmMethod.LessThen
        },
        {
          label: '小于等于',
          value: AlarmMethod.LessThenOrEqual
        },
        {
          label: '大于',
          value: AlarmMethod.GreaterThen
        },
        {
          label: '大于等于',
          value: AlarmMethod.GreaterThenOrEqual
        }
      ]
    };
  },
  watch: {
    dialogVisible: {
      handler(value) {
        if (!value) {
          this.$refs.editDataForm.resetFields();
        }
      }
    }
  },
  created() {
    this.alarmTypeOptions = generateAlarmTypeSelectorData();
  },
  methods: {
    showDialog(uuid) {
      this.remoteDeviceTypeSearch();
      getAlarmRuleDetailApi(uuid)
        .then(res => {
          this.parameterList = [{ id: res.parameter_id, label: `${res.parameter_display_name}(${res.parameter_name})` }];
          this.dataForm.parameterId = res.parameter_id || null;
          this.uuid = res.uuid;
          this.dataForm.name = res.name;
          this.dataForm.alarmMethod = res.alarm_method;
          this.dataForm.alertThreshold = res.alert_threshold;
          this.dataForm.alarmThreshold = res.alarm_threshold;
          this.dataForm.active = res.active;
          this.dataForm.alarmLevel = res.alarm_level;
          this.editConfig.dialogVisible = true;
        })
        .catch(error => Message.error(parseError(error)));
    },
    addrecipient(recipientUuidList) {
      this.dataForm.recipientUuidList = recipientUuidList;
    },
    update() {
      this.btnLoading = true;
      this.deviceTypeUuidList = this.deviceTypeList.map(item => item.uuid);
      this.recipientUuidList = this.recipientList.map(item => item.uuid);
      updateAlarmRuleApi(
        this.uuid,
        this.dataForm.name,
        this.dataForm.parameterId,
        this.dataForm.alarmMethod,
        this.dataForm.alertThreshold,
        this.dataForm.alarmThreshold,
        this.dataForm.active
      )
        .then(res => {
          Message.success('更新成功');
          this.dialogVisible = false;
          this.$emit('refresh');
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.btnLoading = false));
    },
    remoteDeviceTypeSearch(query) {
      this.remoteLoading = true;
      queryDeviceTypeListApi(query, 10)
        .then(deviceTypeList => (this.deviceTypeList = deviceTypeList))
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.remoteLoading = false));
    },
    remoteParameterSearch(name) {
      queryDeviceParameterListApi(name, 10)
        .then(
          res =>
            (this.parameterList = res.map(parameter => {
              return {
                id: parameter.id,
                label: `${parameter.display_name}(${parameter.name})`
              };
            }))
        )
        .catch(error => Message.error(parseError(error)));
    }
  }
};
</script>

<style lang="scss" scoped>
.input {
  width: 300px;
}
/deep/.el-form-item {
  margin-bottom: 22px !important;
}
</style>
